<template>
	<view class="container">
		<!-- 个人信息区 -->
		<view class="profile-card">
			<view class="avatar-container">
				<image class="avatar" mode="aspectFill" :src="avatarUrl"  />
			</view>
			<view class="info-container">
				<view class="name-line">
					<text class="username">{{nickName}}</text>
					<image src="/static/icons/logout.png" class="logout" @click="showPopup"></image>
				</view>
				<view class="bind-status">
					<uni-icons type="weixin" size="16" color="#f5f5f5"></uni-icons>
					<text class="status-text">已绑定微信</text>
				</view>
			</view>
		</view>
		<!-- 我的设备区域 -->
		<view class="device-section">	
			<text class="section-title">我的设备</text>
			<scroll-view class="device-list" scroll-x="true" shows-horizontal-scroll-indicator="false">
				<view class="device-card" v-for="(item, index) in deviceList" :key="index">
					<image mode="aspectFit" class="device-image" @click="navigateToDetail(item.deviceId)"
					      v-if="item.deviceType === 1" 
					      :src="item.onlineStatus === 1 ? OnlineImg : OfflineImg"
					></image>
					<image mode="aspectFit" class="device-image" @click="navigateToDetail(item.deviceId)"
					      v-else 
					      :src="item.onlineStatus === 1 ? OnlineImg : OfflineImg"
					></image>
					
					<text class="device-name">{{ item.deviceName }}</text>
					<view>
						<text class="device-status" :style="{ color: item.onlineStatus == 1 ? '#09BB07' : '#999' }">
						{{ item.onlineStatus == 1 ? '在线' : '离线' }}
						</text>
						<uni-icons type="trash" size="18" color="#FF3B30" @click="handleDelete(item.deviceId,item.deviceName)"/>
					</view>
					
					<!-- 删除确认弹框-->
					<uni-popup ref="popup" type="center" :mask-click="true" mask-background-color="rgba(0,0,0,0)" @change="popupChange">
						<view class="loading-box">
							<view class="title">提示</view>
							<view class="desc">确定要解绑设备吗？</view>
						    
						    <view class="button-group">
						      <button class="btn cancel-btn" @click="hidePopup">取消 </button>
						      <button class="btn confirm-btn" @click="confirmDeletion">确认</button>
						    </view>
						</view>
					</uni-popup>
					
				</view>
			</scroll-view>		
		</view>
    <!-- 设置项列表或类似容器 -->
    <view class="settings-list">
		<view class="list-item" @tap="goToUserManual">
			<!-- 使用说明入口 -->
			<view class="item-content">
				<image class="item-icon" src="/static/icons/Impro_info.png" mode="aspectFit"></image>
				<text class="item-text">使用说明</text>
			</view>
			<image class="arrow-icon" src="/static/icons/arrow-right.png" mode="aspectFit"></image>
		</view>
      <!-- 问题反馈入口 -->
      <view class="list-item" @tap="goToFeedback">
        <view class="item-content">
          <image class="item-icon" src="/static/icons/question-mark.png" mode="aspectFit"></image>
          <text class="item-text">问题反馈</text>
        </view>
        <image class="arrow-icon" src="/static/icons/arrow-right.png" mode="aspectFit"></image>
      </view>
      <!-- ... 其他设置项 ... -->
    </view>	
	
	
	
	
	
	<!--弹框提示-->
	<view class="container">
	    <custom-popup
	      ref="popupRef"
	      title="提示"
	      :buttons="buttons"
	      @close="handleClose"
	      @maskClick="handleMaskClick"
	      @buttonClick="handleButtonClick"
	    >
		<text>确定要退出登录吗？</text>
	    </custom-popup>
	  </view>
	  
	  
	<!-- 底部导航栏 -->
	<view class="tab-bar">
		  <view class="tab-item" @click="switchTab('myDevices')">
			<image src = "/static/icons/device1.png" class="device"></image>
			<text  class="tab-text">设备</text>
		  </view>
		  <view class="tab-item" @click="switchTab('userInfo')">
			<image src = "/static/icons/user1.png" class="user"></image>
			<text class="tab-text, active">我的</text>
		  </view>
		</view>
	</view>
</template>
<script lang="ts" setup>
	import { ref,onMounted} from 'vue';
	import { onShow,onLoad } from '@dcloudio/uni-app';
	import CustomPopup from '@/components/custom-popup.vue'
	import { deleteDevice, getDeviceList } from '../../app/device';
	import { removeStorage } from '../../utils/storage';
	import { wechatLogout} from '../../api/userApi'; // 引入封装的请求
	import { deviceOnlineImg,deviceOfflineImg } from '../../config/index';
	
	// const popupRef = ref<InstanceType<typeof UniPopup> | null>(null);
	const nickName = uni.getStorageSync("userInfo").nickname;
	const avatarUrl = uni.getStorageSync("userInfo").avatarUrl
	const currentTab = ref('userInfo');
	const activeTab = ref('mine');
	const OnlineImg = deviceOnlineImg;
	const OfflineImg = deviceOfflineImg;
	let SelectDeviceId: string | number;
	const deviceList = ref<Array<{
	  id: string 
	  deviceType:1
	  deviceId: string 
	  deviceName: string
	  onlineStatus: 0 | 1
	  activeTime?: Date
	  firmwareVersion?: string
	  detailImage: string
	}>>([])
	
	//自定义popup弹框
	interface ButtonItem {
	  text: string
	  type?: 'primary' | 'warn' | 'default'
	  action?: () => void | Promise<void>
	}
	 
	const popupRef = ref<InstanceType<typeof CustomPopup> | null>(null)
	 
	const buttons = ref<ButtonItem[]>([
	  {
	    text: '取消',
	    type: 'default',
	    action: () => {
	      console.log('取消按钮点击')
	      return new Promise((resolve) => {
	        setTimeout(() => {
	          resolve(true)
	        }, 500)
	      })
	    }
	  },
	  {
	    text: '确认',
	    type: 'primary',
	    action: () => {
	      console.log('确认按钮点击')
	      return new Promise((resolve) => {
	        setTimeout(() => {
	          resolve(true)
	        }, 500)
	      })
	    }
	  }
	])
	 
	const showPopup = () => {
	  popupRef.value?.open()
	}
	 
	const handleClose = () => {
	  console.log('弹出层关闭')
	}
	 
	const handleMaskClick = () => {
	  console.log('点击了遮罩层')
	}
	 
	const handleButtonClick = (button: ButtonItem) => {
	  console.log('按钮点击:', button.text)
	}
	
	
	
	
	//底部跳转
	const switchTab = (tab: string) => {
	  currentTab.value = tab;
	  uni.switchTab({
		url: `/pages/${tab}/${tab}`
	  });
	};

	const showLogoutConfirm = () => {
		uni.showModal({
			title: '提示',
			content: '确定要退出登录吗？',
			success: async (res) => {
				if (res.confirm) {
					// 退出登录
					await wechatLogout();
					removeStorage(['token','userInfo','AlertLogin']),
					uni.showToast({
						title: '退出成功',
						icon: 'success'
					});
				// 实际项目中这里应该是退出登录的逻辑
					uni.redirectTo({
						url: '/pages/login/login'
					})
				}
			}
		});
	};
	
	
	const confimDelete = async (id: string | number) =>{
		if (!id) return
		try{
			return await deleteDevice(id)
		}
		catch(err){
			console.error('删除设备失败',err)
		}
	}
	

	const openPopup = (id: string) => {
		SelectDeviceId = id;
		console.log('SelectDeviceId',SelectDeviceId);
		popup.value?.open();
		
	};
	const  hidePopup = () => {
	  if (popup.value) {
		popup.value.close();
	  }
	}
	const popupChange = (e: { show: boolean }) => {
	  console.log('弹框状态变化:', e.show);
	};
	const confirmDeletion = async () => {
	  //删除设备
	  const result = await confimDelete(SelectDeviceId);
	  if(result){
		deviceList.value = deviceList.value.filter(device => device.id !== SelectDeviceId);
		uni.showToast({
			title: '删除成功',
			icon: 'success'
		});
		await fetchDeviceList()
	  }else{
		uni.showToast({
			title: '设备删除失败',
			icon: 'none'
		});
	  }
	  hidePopup();
	}
	
	const handleDelete = (id: string, name: string) => {
		uni.showModal({
			title: '提示',
			content: `确定要注销设备"${name}"吗？`,
			success: async (res) => {
				if (res.confirm) {
					//删除设备
					const result = await confimDelete(id)
					if(result){
						deviceList.value = deviceList.value.filter(device => device.id !== id);
						uni.showToast({
							title: '删除成功',
							icon: 'success'
						});
						await fetchDeviceList()
					}else{
						uni.showToast({
							title: '设备删除失败',
							icon: 'none'
						});
					}
					
				}
			}
		});
	};
	
	const navigateToDetail = (deviceId: string ) => {
	  uni.navigateTo({
	    url: `/pages/deviceDetail/deviceDetail?deviceId=${deviceId}`
	  });
	};
	
	onShow(()=>{
		fetchDeviceList()
	});
	
	const fetchDeviceList = async () =>{
		try{
			const res = await getDeviceList()
			deviceList.value = res.data||[]
		}catch(err){
			console.error('获取设备失败',err)
			uni.showToast({
				title:'获取设备失败',
				icon:'none'
			})
		}
	}
	
	// 跳转到问题反馈提交页
	const goToFeedback = () => {
		uni.navigateTo({
		  url: `/pages/feedback/feedback`,
		});
	};
	
	// 跳转到完善资料页
	const goToComplateProfile = () => {
		uni.navigateTo({
		  url: `/pages/complateProfile/complateProfile`,
		});
	};
	
	// 跳转到使用说明页面
	const goToUserManual = () => {
		uni.navigateTo({
		  url: `/pages/userManual/userManual`,
		});
	};
	
</script>
<style>
	page {
		height: 100%;
		background-color: #f5f5f5;
	}
	.container {
		display: flex;
		flex-direction: column;
		height: 100%;
		padding: 20rpx 24rpx 120rpx;
		box-sizing: border-box;
	}
	/* 个人信息区样式 */
	.profile-card {
		display: flex;
		background-color: #fff;
		border-radius: 16rpx;
		padding: 32rpx;
		margin-bottom: 32rpx;
		box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.05);
		position: relative;
		
		background: linear-gradient( 220deg, #3986FD 0%, #3986FD 53%, #5FA3F9 100%);
	}
	.avatar-container {
		width: 160rpx;
		height: 160rpx;
		margin-right: 32rpx;
	}
	.avatar {
		width: 100%;
		height: 100%;
		border-radius: 50%;
		background-color: #eee;
	}
	.info-container {
		flex: 1;
		display: flex;
		flex-direction: column;
		justify-content: center;
	}
	.name-line {
		display: flex;
		justify-content: space-between;
		align-items: center;
		margin-bottom: 16rpx;
		width: 100%;
	}
	.username {
		font-size: 32rpx;
		font-weight: bold;
		color: #f5f5f5;
	}
	.logout-btn {
		margin: 0;
		padding: 0 16rpx;
		height: 48rpx;
		line-height: 48rpx;
		font-size: 24rpx;
		display: flex;
		align-items: center;
		gap: 4rpx;
	}
	.bind-status {
		display: flex;
		align-items: center;
		margin-bottom: 16rpx;
	}
	.status-text {
		font-size: 26rpx;
		color: #f5f5f5;
		margin-left: 8rpx;
	}
	.phone-container {
		display: flex;
		align-items: center;
	}
	.phone-text {
		font-size: 26rpx;
		color: #666;
		margin-right: 16rpx;
	}
	.bind-btn {
		margin: 0;
		padding: 0 16rpx;
		height: 48rpx;
		line-height: 48rpx;
		font-size: 24rpx;
	}
	/* 我的设备区域样式 */
	.device-section {
		background-color: #fff;
		border-radius: 16rpx;
		padding: 32rpx;
		margin-bottom: 32rpx;
		box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.05);
		position: relative;
	}
	.section-title {
		font-size: 28rpx;
		color: #333;
		font-weight: bold;
		margin-bottom: 32rpx;
		display: inline-block;
	}
	.add-device-btn {
		position: absolute;
		right: 32rpx;
		top: 32rpx;
		padding: 0 16rpx;
		height: 48rpx;
		line-height: 48rpx;
		font-size: 24rpx;
		display: inline-flex;
		align-items: center;
		gap: 4rpx;
	}
	.device-list {
		white-space: nowrap;
		width: 100%;
	}
	.device-card {
		display: inline-flex;
		flex-direction: column;
		align-items: center;
		width: 160rpx;
		margin-right: 32rpx;
		padding: 20rpx 0;
		position: relative;
	}
	.remove-icon {
		position: absolute;
		top: 8rpx;
		right: 8rpx;
		background: #fff;
		border-radius: 50%;
		padding: 4rpx;
		box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.1);
	}
	.device-name {
		font-size: 24rpx;
		color: #333;
		margin: 16rpx 0 8rpx;
		white-space: nowrap;
		overflow: hidden;
		text-overflow: ellipsis;
		width: 100%;
		text-align: center;
	}
	.device-status {
		font-size: 22rpx;
	}
	.empty-device {
		display: flex;
		flex-direction: column;
		align-items: center;
		padding: 64rpx 0;
	}
	.empty-text {
		font-size: 28rpx;
		color: #999;
		margin-bottom: 32rpx;
	}
	.register-btn {
		width: 200rpx;
		height: 72rpx;
		line-height: 72rpx;
	}
	/* 底部导航栏样式 */
	.tab-bar {
		position: fixed;
		bottom: 0;
		left: 0;
		right: 0;
		display: flex;
		height: 100rpx;
		background-color: #fff;
		box-shadow: 0 -2rpx 8rpx rgba(0, 0, 0, 0.05);
		z-index: 100;
	}
	.tab-item {
		flex: 1;
		display: flex;
		flex-direction: column;
		justify-content: center;
		align-items: center;
	}
	.tab-item.active uni-icons {
		color: #2979ff;
	}
	.tab-item.active .tab-text {
		color: #2979ff;
	}
	.tab-text {
		font-size: 22rpx;
		margin-top: 8rpx;
		color: #666;
	}
	
	.device-image {
		width: 150rpx;
		height: 150rpx;
	}
	
	


.feedback-entry-section {
  margin-top: 20rpx;
  background-color: #FFFFFF;
}

.list-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 32rpx 30rpx;
  background-color: #FFFFFF;
}

/* 修改 &:active */
.list-item:active {
  background-color: #f9f9f9;
}

.list-item {
  border-bottom: 1rpx solid #EEEEEE;
}
.feedback-entry-section > .list-item:last-child {
    border-bottom: none;
}

.list-item .item-content { 
  display: flex;
  align-items: center;
}

.list-item .item-icon {
  width: 52rpx;
  height: 52rpx;
  margin-right: 16rpx;
}

.list-item .item-text {
  font-size: 30rpx;
  color: #333333;
}


.list-item .arrow-icon {
  width: 46rpx;
  height: 46rpx;
}

.settings-list {
  margin-top: 20rpx;
  background-color: #FFFFFF;
  border-radius: 16rpx;
  overflow: hidden;
}

.settings-list .list-item {
  border-bottom: 1rpx solid #EEEEEE;
}
.settings-list .list-item:last-child {
  border-bottom: none;
}

.loading-text {
	  margin-top: 10rpx;
	  color: #fff;
	  font-size: 32rpx;
	}
	
	.button-group {
	  display: flex;
	  justify-content: space-between;
	  gap: 24rpx;
	}
	.btn {
	  flex: 1;
	  
	  font-size: 32rpx;
	  display: flex;
	  align-items: center;
	  justify-content: center;
	}
	
	.cancel-btn {
	  background-color: #F5F5F5 !important;
	  color: #666666 !important;
	}
	
	.confirm-btn {
	  background: linear-gradient(90deg, #4A90E2 0%, #5C9EFF 100%) !important;
	  color: #FFFFFF !important;
	}
	
	.content {
	  text-align: center;
	  margin-bottom: 48rpx;
	}
	
	.title {
	  font-size: 36rpx;
	  color: #FFFFFF;
	  font-weight: 500;
	  padding: 50rpx 100rpx 0 115rpx;
	      line-height: 42rpx;
	      box-sizing: border-box;
	}
	
	.desc {
	  font-size: 32rpx;
	  color: #FFFFFF;
	  line-height: 2.5;
	}
	.logout{
		width: 37rpx;
		height: 35rpx;
		
	}
	.device {
		width: 60rpx;
		height: 60rpx;
	}
	.user {
		width: 60rpx;
		height: 60rpx;
	}
	
	
	
	
</style>
